package mirrormonkey.rpc.module;

import mirrormonkey.framework.EntityProvider;
import mirrormonkey.framework.entity.EntityData;
import mirrormonkey.rpc.member.RpcMethodData;
import mirrormonkey.rpc.messages.RpcCallMessage;

import com.jme3.network.Message;
import com.jme3.network.MessageConnection;
import com.jme3.network.MessageListener;

public class RpcCallListener implements MessageListener<MessageConnection> {

	public final EntityProvider provider;

	public RpcCallListener(EntityProvider provider) {
		this.provider = provider;
	}

	@Override
	public void messageReceived(MessageConnection source, Message message) {
		RpcCallMessage castMessage = (RpcCallMessage) message;
		EntityData data = provider.getData(castMessage.entityId);
		Message response;
		if ((response = data
				.getStaticData(source)
				.getData(castMessage.methodId, RpcMethodData.class)
				.executeFromRemote(source, data, castMessage, provider.appState)) != null) {
			source.send(response);
		}
	}

}
